<template>
  <div class="container">
    <q-page class="terminal-crane-page">
      <!-- 其他组件 -->
      <TerminalHeader :rollerList="filterRollerList" />
      <LeftInfo :craneNo="craneNo" :saddleList="saddleList" :parkingList="parkingList" />
      <MatInfo :craneNo="craneNo" />
      <ProductionPlan :orderData="orderData" :craneNo="craneNo" />
      <VideoMain />
      <TaskMain />
      <TaskDetail />

      <!-- StockNo 显示 -->
      <!-- <div class="stock-no-display">{{ stockNo }}</div> -->
      <div v-if="stockNo" class="stock-no-display">「{{ stockNo }}」</div>
      <RadarChart :craneNo="craneNo" :highlighted="highlighted" :number="number" />

      <!-- 弹窗 -->
      <q-dialog v-model="showDialog" persistent>
        <q-card class="alarm-card">
          <q-card-section :class="requiresConfirmation ? 'alarm-card-section' : 'alarm-card-section no-confirm'">
            <div class="alarm-message">{{ alarmMessage }}</div>
          </q-card-section>
          <q-card-actions v-if="requiresConfirmation">
            <q-btn @click="confirmAlert" label="确认" class="custom-btn-color scaled-btn" />
          </q-card-actions>
        </q-card>
      </q-dialog>

      <div class="safety-doors">
        <div
          v-for="(status, index) in filteredSafetyDoors"
          :key="index"
          :class="['door-status', { 'unlocked-flash': !status.locked }]"
        >
          安全门{{ status.doorId }}: {{ status.locked ? '锁定' : '解锁' }}
        </div>
      </div>

      <div class="crane-more">
        <div>大车: {{ xAct }}</div>
        <div>小车: {{ yAct }}</div>
        <!-- <div>重量: {{ weight }}</div> -->
        <!-- <div :class="getDistanceClass(nextCraneDis)" v-if="craneNo == '03'">
          2号车: {{ (nextCraneDis / 1000).toFixed(1) }}米
        </div> -->
        <!-- <div :class="getDistanceClass(nextCraneDis)" v-if="craneNo == '01'"></div> -->
        <!-- <div :class="getDistanceClass(nextCraneDis)" v-if="craneNo == '02'">
          1号车: {{ (nextCraneDis / 1000).toFixed(1) }}米
        </div> -->
        <!-- <div :class="getDistanceClass(nextCraneDis)" v-if="craneNo == '04'"> -->
          <!-- 3号车: {{ (nextCraneDis / 1000).toFixed(1) }}米 -->
        <!-- </div> -->
        <!-- <div :class="getDistanceClass(nextCraneDis)" v-if="craneNo == '05'">
          4号车: {{ (nextCraneDis / 1000).toFixed(1) }}米
        </div> -->
        <!-- <div :class="getDistanceClass(nextCraneDis)" v-if="craneNo == '06'">
          5号车: {{ (nextCraneDis / 1000).toFixed(1) }}米
        </div> -->
        <!-- <div :class="getDistanceClass(preCraneDis)" v-if="craneNo == '02'">
          3号车: {{ (preCraneDis / 1000).toFixed(1) }}米
        </div> -->
        <!-- <div :class="getDistanceClass(preCraneDis)" v-if="craneNo == '03'"></div> -->
        <!-- <div :class="getDistanceClass(preCraneDis)" v-if="craneNo == '04'">
          5号车: {{ (preCraneDis / 1000).toFixed(1) }}米
        </div> -->
        <!-- <div :class="getDistanceClass(preCraneDis)" v-if="craneNo == '05'">
          6号车: {{ (preCraneDis / 1000).toFixed(1) }}米
        </div> -->
        <!-- <div v-if="craneNo == '06'"></div> -->
      </div>

      <!-- 条件渲染的涟漪效果 -->
      <svg v-if="isEmpty" class="ripple-effect" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 100">
        <defs>
          <radialGradient id="grad1" cx="50%" cy="50%" r="60%" fx="50%" fy="50%">
            <stop offset="0%" style="stop-color: rgba(255, 0, 0, 0); stop-opacity: 0" />
            <stop offset="80%" style="stop-color: rgba(255, 0, 0, 0.5); stop-opacity: 0.4" />
          </radialGradient>
        </defs>
        <!-- 第一个椭圆形涟漪 -->
        <ellipse class="ripple" cx="100" cy="50" rx="100" ry="50" />
        <!-- 第二个椭圆形涟漪 -->
        <ellipse class="ripple" cx="100" cy="50" rx="60" ry="30" />
        <!-- 实心圆点 -->
        <circle class="center-dot" cx="100" cy="50" r="9" />
      </svg>
    </q-page>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, computed } from 'vue';
import TerminalHeader from './header/index.vue';
import LeftInfo from './left-info/index.vue';
import MatInfo from './mat-info/index.vue';
import ProductionPlan from './plan-production/index.vue';
import VideoMain from './video/index.vue';
import TaskMain from './task/index.vue';
import TaskDetail from './task-detail/index.vue';
import RadarChart from './radar-chart/index.vue';
import { useWebsocket } from 'src/pages/_sys/use-websocket1';
import { SaddleRow, ParkingRow } from './left-info/model';
import { useTerminalStore } from './store';
import { getScaleX, getScaleY, parseOrderData1 } from './radar-chart/utils';

export default defineComponent({
  name: 'terminal-crane',

  components: {
    TerminalHeader,
    LeftInfo,
    MatInfo,
    ProductionPlan,
    VideoMain,
    TaskMain,
    TaskDetail,
    RadarChart,
  },

  setup() {
    const terminalStore = useTerminalStore();
    const craneNo = ref(localStorage.getItem('craneNo') || '');
    const saddleList = ref<SaddleRow[]>([]);
    const parkingList = ref<ParkingRow[]>([]);
    const obj = ref<Record<string, any>>({});
    const stockNo = ref<string>(''); // 添加 stockNo 变量
    const orderData = ref<any[]>([]);
    const highlighted = ref<string>(''); // 存储 highlighted 的值
    const number = ref<number>(0); // 存储 number 的值

    // 弹窗相关
    const showDialog = ref(false);
    const alarmMessage = ref('');
    const requiresConfirmation = ref(false);
    const isEmpty = ref(false); // 新增 isEmpty 变量

    // 定义类型
    interface SafetyDoor {
      doorId: number;
      locked: boolean;
    }
    // 使用 ref 包装并指定类型
    const safetyDoors = ref<SafetyDoor[]>([
      { doorId: 1, locked: true },
      { doorId: 2, locked: true },
      { doorId: 3, locked: true },
      { doorId: 4, locked: true },
      { doorId: 5, locked: true },
    ]);
    const filteredSafetyDoors = computed(() => {
      if (['01', '02', '03'].includes(craneNo.value)) {
        return safetyDoors.value.filter(door => [1, 2, 3].includes(door.doorId));
      } else if (['04', '05', '06'].includes(craneNo.value)) {
        return safetyDoors.value.filter(door => [4, 5].includes(door.doorId));
      }
      return []; // 如果行车号不符合要求，则不显示任何安全门
    });

    function updateSafetyDoors(safetyDoorData: Record<string, number>) {
      safetyDoors.value = safetyDoors.value.map(door => ({
        ...door,
        locked: safetyDoorData[`sGate${door.doorId}`] === 0, // 0: Locked, 1: Unlocked
      }));
    }
    const rollerList = ref([
      { rollerNo: '13', lock: 0, type: 'A' },
      { rollerNo: '14', lock: 0, type: 'A' },
      { rollerNo: '23', lock: 0, type: 'A' },
      { rollerNo: '24', lock: 0, type: 'A' },
      { rollerNo: '15', lock: 0, type: 'B' },
      { rollerNo: '16', lock: 0, type: 'B' },
      { rollerNo: '25', lock: 0, type: 'B' },
      { rollerNo: '26', lock: 0, type: 'B' },
    ]);
    const xAct = ref(0); // 大车位置
    const yAct = ref(0); // 小车位置
    const weight = ref(0); // 重量

    const nextCraneDis = ref(0); // 车号-1 的距离

    const preCraneDis = ref(0); // 车号+1的距离

    const filterRollerList = computed(() => {
      return rollerList.value.filter(v => {
        return (
          (['01', '02', '03'].includes(craneNo.value) && v.type === 'A') ||
          (!['01', '02', '03'].includes(craneNo.value) && v.type === 'B')
        );
      });
    });
    const getDistanceClass = (distance: number) => {
      return distance < 20000 ? 'red-flash' : ''; // 小于20米的字体闪烁
    };

    useWebsocket(
      'CRANE_WEBSOCKET,NEW_CRANE_INDEX_ORDERS,NEW_CRANE_INDEX_EQU_SADDLE,NEW_CRANE_INDEX_PARK_INFO,ROLLER_DATA,CLTS_ALARM_WEB_SOCKET,CRANE_INDEX_ORDERS,L1_S_GATA_DATA',
      payload => {
        if (payload.topic === 'NEW_CRANE_INDEX_ORDERS') {
          console.log('NEW_CRANE_INDEX_ORDERS');
          const craneData = payload.data?.[craneNo.value];
          if (craneData) {
            if (JSON.stringify(craneData) !== JSON.stringify(orderData.value)) {
              obj.value = {};
              orderData.value = craneData;
              const scaleX = getScaleX(craneData);
              const scaleY = getScaleY(craneData);
              const parseData = parseOrderData1(craneData, scaleX, scaleY, obj.value, 1000, 600);
              terminalStore.orderData = parseData;
            }
          }
        } else if (payload.topic === 'NEW_CRANE_INDEX_EQU_SADDLE') {
          if (payload.data?.[craneNo.value]) {
            saddleList.value = payload.data?.[craneNo.value];
          }
        } else if (payload.topic === 'NEW_CRANE_INDEX_PARK_INFO') {
          if (payload.data?.[craneNo.value]) {
            parkingList.value = payload.data?.[craneNo.value];
          }
        } else if (payload.topic === 'ROLLER_DATA') {
          rollerList.value.forEach(v => {
            if (v.rollerNo === payload.data.rollerNo) {
              v.lock = payload.data.lock;
            }
          });
        } else if (payload.topic === 'CLTS_ALARM_WEB_SOCKET') {
          const alarmList = payload.data;
          const { craneNo: alarmCraneNo, confirm, msg } = alarmList;

          if (alarmCraneNo?.length === 0 || alarmCraneNo?.includes(craneNo.value)) {
            alarmMessage.value = msg;
            requiresConfirmation.value = confirm;
            showDialog.value = true;

            if (!confirm) {
              setTimeout(() => {
                showDialog.value = false;
              }, 5000);
            }
          }
        } else if (payload.topic === 'CRANE_WEBSOCKET') {
          // 新增处理 isEmpty 字段
          const craneData = payload.data?.[craneNo.value];
          if (craneData) {
            isEmpty.value = craneData.isEmpty === 1;
            stockNo.value = craneData.stockNo || ''; // 更新 stockNo 的值
            xAct.value = craneData.xAct; // 获取大车位置
            yAct.value = craneData.yAct; // 获取小车位置
            weight.value = craneData.weight; // 获取重量
            nextCraneDis.value = craneData.nextCraneDis;

            preCraneDis.value = craneData.preCraneDis; // 获取邻车距离
          }
        } else if (payload.topic === 'L1_S_GATA_DATA') {
          // 处理安全门状态数据
          const safetyDoorData = payload.data;
          updateSafetyDoors(safetyDoorData);
        }
      },
    );

    const displayedSafetyDoors = computed(() => {
      // 根据 craneNo 显示对应安全门的状态
      if (['1', '2', '3'].includes(craneNo.value)) {
        return safetyDoors.value.filter(door => [1, 2, 3].includes(door.doorId));
      } else if (['4', '5', '6'].includes(craneNo.value)) {
        return safetyDoors.value.filter(door => [4, 5].includes(door.doorId));
      }
      return [];
    });
    const confirmAlert = () => {
      showDialog.value = false;
    };

    onMounted(() => {
      if (!craneNo.value) {
        console.error('Crane No not found in local storage');
      } else {
        console.log('Selected Crane No:', craneNo.value);
      }
    });

    return {
      craneNo,
      saddleList,
      parkingList,
      rollerList,
      filterRollerList,
      showDialog,
      alarmMessage,
      requiresConfirmation,
      orderData,
      confirmAlert,
      isEmpty, // 返回 isEmpty 变量
      highlighted, // 返回 highlighted 变量
      number, // 返回 number 变量
      stockNo, // 返回 stockNo 变量
      xAct,
      yAct,
      weight,
      nextCraneDis,

      preCraneDis,
      getDistanceClass,
      safetyDoors,
      displayedSafetyDoors,
      filteredSafetyDoors,
    };
  },
});
</script>

<style lang="scss" scoped>
@font-face {
  font-family: 'Furore';
  src: url('src/assets/fonts/Furore.otf') format('opentype');
}
@font-face {
  font-family: 'AlibabaPuHuiTi';
  src: url('src/assets/fonts/AlibabaPuHuiTi-3-85-Bold.ttf') format('truetype');
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100vw;
  height: 100vh;
  background-color: #000;
}

.terminal-crane-page {
  width: 1024px;
  height: 768px;
  background-color: #000;
  overflow: hidden;
  font-family: 'AlibabaPuHuiTi', sans-serif;
  background-image: url('src/assets/terminal/bg.png');
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  display: flex;
  flex-direction: column;
}
.alarm-card {
  background-image: url('src/assets/terminal/alarm.png');
  background-size: contain; // 确保背景图片显示完整
  background-position: center;
  background-repeat: no-repeat;
  background-color: rgba(0, 0, 0, 0.8);
  color: #fff;
  width: 300px;
  max-width: 90%;
  margin: 0 auto;

  // 增加最小高度，确保背景图片不被压缩
  min-height: 200px;
  padding-bottom: 20px; // 增加下部填充
}

.alarm-card-section {
  padding: 10px;
  text-align: left;
  color: #fff;

  // 增加最小高度以确保背景撑开
  min-height: 100px;
}
.alarm-message {
  font-size: 14px;
  color: #fff;
  margin-top: 60px;
  margin-left: 20px;
  max-width: 80%; /* 设置最大宽度，限制文字行长度 */
  word-break: break-word; /* 防止单词溢出 */
}

.custom-btn-color {
  background-color: #ff386b;
  color: #fff;
}
.alarm-card-section.no-confirm {
  padding: 10px;
  text-align: left;
  color: #fff;
  margin-top: 18px; /* 调整这个值，使文字居中 */
  margin-left: 20px;
  max-width: 80%;
  word-break: break-word;
}

.scaled-btn {
  transform: scale(0.8); /* 调整缩放比例 */
  position: relative;
  top: -10px; /* 向上移动 5px */
  left: 200px; /* 向右移动 5px */
}

.ripple-effect {
  position: absolute;
  top: 45.1%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 200px;
  height: 100px;
}

.ripple {
  fill: url(#grad1);
  stroke: rgba(255, 0, 0, 0.5);
  stroke-width: 0;
}

.center-dot {
  fill: rgba(255, 0, 0, 0.9);
}
.stock-no-display {
  position: absolute;
  top: 80px; /* 调整为距离顶部的距离 */
  right: 20px; /* 调整为距离右侧的距离 */
  font-size: 30px; /* 字体大小 */
  color: #fff; /* 字体颜色 */
  font-family: 'Furore';
  padding: 26px 12px; /* 内边距 */
  background-image: url('src/assets/terminal/1_crane_bg.png');
  background-repeat: no-repeat; /* 防止背景图片重复 */
  background-position: center; /* 确保背景图片居中对齐 */
  z-index: 9999; /* 设置一个非常高的层级值 */
  pointer-events: auto; /* 允许交互 */
}
.safety-doors {
  position: absolute;
  top: 210px;
  left: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.4);
  padding: 10px;
  border-radius: 8px;
  color: #fff;
}

.door-status {
  font-size: 16px;
  margin: 4px 0;
}

.unlocked-flash {
  color: red;
  animation: flash 1s infinite;
}

@keyframes flash {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}
.red-flash {
  color: red;
  animation: flash 1s infinite;
}

@keyframes flash {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

.crane-more {
  position: absolute;
  top: 240px; /* 调整为距离顶部的距离 */
  right: 20px; /* 调整为距离右侧的距离 */
  font-size: 20px; /* 字体大小 */
  color: #fff; /* 字体颜色 */
  padding: 26px 12px; /* 内边距 */
}

.unlocked-flash {
  color: red;
  animation: flash 1s infinite;
}

@keyframes flash {
  0%,
  50%,
  100% {
    opacity: 1;
  }
  25%,
  75% {
    opacity: 0.5;
  }
}
</style>
